<?php

!defined('IN_NOVA') && exit('Access Denied!');

class Admin extends Application {

	public function __construct() {
		global $cache,$db;
		parent::__construct();

		// 初始化缓存
		//$cache_list = array( 'config', 'category', 'count', 'tag' );
		if( $cache->config == NULL ) {
			$content = $db->fetch_all( 'SELECT * FROM `' . DB_PREFIX . 'set' );
			$cache->set( 'config', $content[0], 0 );
		}
		if( $cache->tag == NULL ) {
			$content = array();
			$query = $db->query( 'SELECT * FROM `' . DB_PREFIX . 'tags` ORDER BY t_id Asc' );
			while ( $row = $db->fetch_array( $query ) ) {
				$content[$row['t_id']] = array( 't_name' => $row['t_name'], 't_num' => $row['t_num'], );
			}
			$cache->set( 'tag', $content, 0 );
			unset( $query, $row );
		}
		if( $cache->category == NULL ) {
			global $db;
			$content = array();
			$query = $db->query( 'SELECT cid,pid,name,alias,articlenum,description FROM `' . DB_PREFIX . 'category` ORDER BY num ASC,cid DESC' );
			while ( $row = $db->fetch_array( $query ) ){
				$content[$row['cid']] = $row;
			}
			$cache->set( 'category', $content, 0 );
			unset( $query, $row );
		}
		if( $cache->count == NULL ) {
			$content = array(
				'article_num' => $db->result( 'SELECT count(id) FROM `' . DB_PREFIX . 'article` WHERE isdel=False' ),
				'comment_num' => $db->result( 'SELECT count(cid) FROM `' . DB_PREFIX . 'comment` WHERE isdel=False AND articleid<>0' ),
				'guestbook_num' => $db->result( 'SELECT count(cid) FROM `' . DB_PREFIX . 'comment` WHERE isdel=False AND articleid=0' ),
				'user_num' => $db->result( 'SELECT count(u_id) FROM `' . DB_PREFIX . 'user` WHERE u_isdel=False' ),
				'guestbook_num_censor' => $db->result( "SELECT count(cid) FROM `" . DB_PREFIX . "comment` WHERE isshow=0 and isdel=0 and articleid=0" ),
				'comment_num_censor' => $db->result( "SELECT count(cid) FROM `" . DB_PREFIX . "comment` WHERE isshow=0 and isdel=0 and articleid<>0" ),
				'file_num' => $db->result( "SELECT count(ul_id) FROM `" . DB_PREFIX . "upload`" ),
			);
			$cache->set( 'count', $content, 0 );
		}
		unset( $content );
	}

	public function start() {
		global $request,$cache,$user;

		if( $request->get( 'm' ) == NULL ) {
			$request->m = 'index';
		}

		if( !isset( $_SESSION['user_group'] ) ) {
			$_SESSION['user_group'] = 0;
		}

		// 尝试自动登录
		$username = $request->get( APP_PREFIX . 'username', 'C' );
		$password = $request->get( APP_PREFIX . 'password', 'C' );
		if( $username !== NULL && $password !== NULL ){
			if( $user->login( $username, $password ) != 1 ) {
				echo $user->login( $username, $password );
				setcookie( APP_PREFIX . 'username', NULL );
				setcookie( APP_PREFIX . 'password', NULL );
			}
		}
		unset( $username, $password );

		if( !$user->is_super_admin() ) {
			$request->m = 'login';
		}

		// 更新 ohash
		if( $cache->ohash == NULL ) {
			// 这里可以设置超时时间，默认 20 分钟
			$cache->set( 'ohash', get_random_string(8), 1200 );
		} else {
			$cache->set( 'ohash', $cache->ohash, 600 );
		}

		$module = $request->get( 'm' );
		if( method_exists( $this, $module ) ) {
			$this->$module();
		} else {
			$this->page( $module );
		}
	}

	// 页面
	private function page( $name, $page_make = FALSE ) {
		global $theme,$request,$cache;
		//[DEBUG]
		global $log;
		//[/DEBUG]

		// 检查 ohash
		if( ( $cache->ohash != $request->get( 'ohash' ) ) && $name != 'login' && $name != 'index' ) {
			// ohash 验证失败，登录超时或来源非法
			global $user;
			$user->logout();
			echo 'forbidden';
			return;
		}

		// 防止非法的文件包含
		$tmparray = array('/',"\0",'..');
		if( str_replace( $tmparray, '', $name ) != $name ) {
			$theme->err_404();
			return;
		}

		if( is_file( APP_ADMIN .'kernel/' . $name . '.class.php' ) ) {
			include( APP_ADMIN .'kernel/' . $name . '.class.php' );
		} else {
			$this->err_404();
			return;
		}

		//[DEBUG]
		$runtime = microtime( TRUE );
		//[/DEBUG]
		$name = ucwords( $name );
		$page = new $name();
		$page->start();
		//[DEBUG]
		$runtime = microtime( TRUE ) - $runtime;
		if( defined( 'APP_DEBUG' ) && APP_DEBUG === TRUE ) {
			$log->add( '页面处理用时：' . $runtime * 1000 . 'ms。', E_USER_NOTICE );
		}
		//[/DEBUG]
	}

	// 
	private function cache_refresh_all() {
		global $cache;
		$cache->refresh_all( TRUE );
	}

	// 404
	public function err_404() {
		@header( 'HTTP/1.1 404 Not Found' );
		@header( 'status: 404 Not Found' );
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml" lang = "zh-cn">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>Error 404 - Not Found</title>
</head>
<body>
	<h2>Error 404 - Not Found</h2>
</body>
</html>
<?php
	}

	// 分页
	static public function get_navigator( $article_num, $max_per_page, $current_page, $module, $params = '' ){
		if( $article_num < $max_per_page + 1 ) return;

		if( ( $article_num % $max_per_page ) == 0 ){
			$page_num = floor( $article_num / $max_per_page );
		}else{
			$page_num = floor( $article_num / $max_per_page ) + 1;
		}
		if( $current_page > $page_num ) return;

		if( $module == '' ) $module = 'index';

		$leader = '<div class="navigator"><span class="navigator_tip">Pages：' . $current_page . '/' . $page_num . '</span>';

		$i = 1;
		$leader .= '<a href="#" onclick="' . Admin::get_navigator_url( $i, $module, $params ) . '">«</a>';
		if( $current_page != 1 ){
			$i = $current_page - 1;
		}
		$leader .= '<a href="#" onclick="' . Admin::get_navigator_url( $i, $module, $params ) . '">‹</a>';

		if( $current_page > 5 ){
			$leader .= ' …… ';
			for( $i = $current_page - 4 ; $i < $current_page ; $i ++ ){
				$leader .= '<a href="#" onclick="' . Admin::get_navigator_url( $i, $module, $params ) . '">' . $i . '</a>';
			}
		}else{
			for($i = 1 ; $i < $current_page ; $i ++ ){
				$leader .= '<a href="#" onclick="' . Admin::get_navigator_url( $i, $module, $params ) . '">' . $i . '</a>';
			}
		}

		$leader .= '<span class="navigator_current">' . $current_page . '</span>';

		if( $page_num - $current_page > 4 ){
			for($i = $current_page + 1 ; $i < $current_page + 5 ; $i ++ ){
				$leader .= '<a href="#" onclick="' . Admin::get_navigator_url( $i, $module, $params ) . '">' . $i . '</a>';
			}
			$leader .= ' …… ';
		}else{
			for( $i = $current_page + 1 ; $i < $page_num + 1 ; $i ++ ){
				$leader .= '<a href="#" onclick="' . Admin::get_navigator_url( $i, $module, $params ) . '">' . $i . '</a>';
			}
		}

		if( $current_page > $page_num - 1 ){
			$i = $page_num;
		}else{
			$i = $current_page + 1;
		}
		$leader .= '<a href="#" onclick="' . Admin::get_navigator_url( $i, $module, $params ) . '">›</a>';
		$leader .= '<a href="#" onclick="' . Admin::get_navigator_url( $page_num, $module, $params ) . '">»</a></div>';

		return $leader;
	}

	static public function get_navigator_url( $i, $module , $params = '' ) {
		if( $params == '' ) {
			return "ajax_load('" . ADMIN_PATH . "','" . $module . "',null,'" . $i . "');return false;";
		} else {
			return "ajax_load('" . ADMIN_PATH . "','" . $module . "','" . $params . "','" . $i . "');return false;";
		}
	}

}
?>
